package com.neo.subscribe.wechat.service;

import com.alibaba.fastjson.JSON;
import com.neo.subscribe.stamp.service.StampService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class StampMessageService {

    private final StampService stampService;

    private final WxMpService mpService;

    /**
     * 发给指定用户
     *
     * @param openId
     */
    public void sendStampMessage(String openId) {
        try {
            String content = stampService.assembleMessage();
            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(openId).content(content).build();
            mpService.getKefuService().sendKefuMessage(message);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }

    public void sendStampMessage() {
        String content = stampService.assembleMessage();

        WxMpUserList userListResult;
        String nextOpenId = null;
        List<String> openIds;
        do {
            // 获取用户 openIds
            try {
                userListResult = mpService.getUserService().userList(nextOpenId);
            } catch (WxErrorException e) {
                log.error("获取用户列表失败#{}", ExceptionUtils.getFullStackTrace(e));
                break;
            }
            nextOpenId = userListResult.getNextOpenid();
            openIds = userListResult.getOpenids();

            // 逐一发送消息
            for (String openId : openIds) {
                try {
                    WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(openId).content(content).build();
                    log.info("逐一群发消息请求参数 - 2：{}", JSON.toJSONString(message));
                    boolean result = mpService.getKefuService().sendKefuMessage(message);
                    log.info("逐一群发消息请求参数 - 2：{}", result);
                } catch (WxErrorException e) {
                    log.error("逐一群发消息失败#{}", ExceptionUtils.getFullStackTrace(e));
                }
            }
        } while (CollectionUtils.isNotEmpty(openIds));

    }

    /**
     * 群发消息
     */
    public void sendStampMassage() {
        try {
            String content = stampService.assembleMessage();

            WxMpUserList userListResult;
            String nextOpenId = null;
            List<String> openIds;
            do {
                // 获取用户 openIds
                userListResult = mpService.getUserService().userList(nextOpenId);
                nextOpenId = userListResult.getNextOpenid();
                openIds = userListResult.getOpenids();

                if (CollectionUtils.size(openIds) > 1) {
                    // 群发消息
                    WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
                    massMessage.setMsgType(WxConsts.MassMsgType.TEXT);
                    massMessage.setContent(content);
                    massMessage.setToUsers(openIds);
                    log.info("群发消息请求参数 - 1：{}", JSON.toJSONString(massMessage));
                    WxMpMassSendResult massResult = mpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
                    log.info("群发消息响应结果 - 2：{}", JSON.toJSONString(massResult));
                } else {
                    WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(openIds.get(0)).content(content).build();
                    log.info("群发消息请求参数 - 2：{}", JSON.toJSONString(message));
                    boolean result = mpService.getKefuService().sendKefuMessage(message);
                    log.info("群发消息请求参数 - 2：{}", result);
                }
            } while (CollectionUtils.isNotEmpty(openIds));
        } catch (WxErrorException e) {
            log.error("群发消息失败：{}", ExceptionUtils.getFullStackTrace(e));
        }
    }

}
